import os
import sys
import time
from shlex import quote as shlex_quote

from colorama import init, Fore, Style

import lib.utils.log_loader as log_loader
from common.data.element_selectors import CHAT_MESSAGE_ANSWER, CHAT_MESSAGE,LISTEN_STATE
from lib.utils.redis_util import get_redis_client

init(autoreset=True)  # 初始化colorama，并设置颜色自动重置


def clear_screen():
    """
    清除当前终端屏幕。

    该函数没有参数。

    返回值: 无返回值。
    """
    # 使用不同的命令根据操作系统类型来清除屏幕
    os.system(shlex_quote('cls') if os.name == 'nt' else 'clear')


def main_menu():
    while True:
        clear_screen()
        print(Fore.CYAN + Style.BRIGHT + "主菜单:\n")
        print(Fore.YELLOW + "1. 控制")
        print(Fore.YELLOW + "2. 聊天")
        print(Fore.YELLOW + "3. 退出")
        choice = input(Fore.GREEN + "请选择一个选项: ")
        if choice == "1":
            feature_a()
        elif choice == "2":
            feature_chat()
        elif choice == "3":
            print(Fore.RED + "程序退出")
            sys.exit(0)
        else:
            print(Fore.RED + "无效输入，请重新输入！")
        input(Fore.GREEN + "按任意键返回主菜单...")


def feature_a():
    redis_client = get_redis_client()
    while True:
        clear_screen()
        print(Fore.CYAN + Style.BRIGHT + "功能A:\n")
        print(Fore.YELLOW + "1. 退出系统")
        print(Fore.YELLOW + "2. 监控")
        print(Fore.YELLOW + "3. 退出")
        choice = input(Fore.GREEN + "请选择一个选项: ")
        if choice == "1":
            redis_client.set(LISTEN_STATE, 0)
        elif choice == "2":
            monitor_feature()
        elif choice == "3":
            return
        else:
            print(Fore.RED + "无效输入，请重新输入！")


def start_feature():
    print(Fore.GREEN + "功能启动...")
    input(Fore.GREEN + "按任意键返回...")


def monitor_feature():
    print(Fore.GREEN + "正在监控...")
    input(Fore.GREEN + "按任意键返回...")


def feature_chat():
    redis_client = get_redis_client()

    print(Fore.GREEN + Style.BRIGHT + "欢迎来到聊天功能！")
    print(Fore.YELLOW + "输入消息并按回车发送。输入'退出'以结束聊天。\n")

    while True:
        message = input(Fore.GREEN + "你: ")
        if message == '退出':
            print(Fore.RED + "正在退出聊天...")
            break

        # 将输入的消息写入Redis
        redis_client.set(CHAT_MESSAGE, message)

        # 从Redis获取回复并显示
        while not redis_client.exists(CHAT_MESSAGE_ANSWER):
            time.sleep(1)  # 如果还没有回复，继续等待

        # 从Redis获取回复并显示
        response = redis_client.get(CHAT_MESSAGE_ANSWER)
        print(Fore.CYAN + "ChatGPT: " + response)

        # 清除回复，准备下一轮对话
        redis_client.delete(CHAT_MESSAGE_ANSWER)
